package com.chinawayltd.ews.sample.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * cookie操作工具类
 *
 * @author jianeng.li
 */
public class CookiesUtil {

    private static final int INIT_MAP_SIZE = 200;
    /**
     * Token在cookie当中设置的key值
     * */
    public static final String TOKEN_KEY_STRING = "_TOKEN";
    /**
     * Token存活在Cookie当中的有效期设置为7天
     * */
    public static final int TOKEN_VALID_TIME = 60 * 60 * 24 * 7;

    /**
     * 根据名字获取cookie
     *
     * @param request
     * @param name cookie名字
     * @return
     */
    public static String getCookieByName(HttpServletRequest request, String name) {
        Map<String, Cookie> cookieMap = readCookieMap(request);
        if (cookieMap.containsKey(name)) {
            Cookie cookie = cookieMap.get(name);
            if (cookie != null) {
                return cookie.getValue();
            }
            return null;
        } else {
            return null;
        }
    }

    /**
     * 将cookie封装到Map里面
     *
     * @param request
     * @return 使用Map来保存cookie的key和value对
     */
    private static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<>(INIT_MAP_SIZE);
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }

    /**
     * 保存Cookies
     *
     * @param response
     *            servlet请求
     * @param name
     *            cookie名称
     * @param value
     *            保存值
     * @param time
     *            cookie有效时间，单位为秒
     * @return response对象
     */
    public static HttpServletResponse setCookie(HttpServletResponse response, String name,
                                                String value, int time) {
        // new一个Cookie对象,键值对为参数
        Cookie cookie = new Cookie(name, value);
        // tomcat下多应用共享
        cookie.setPath("/");
        // 如果cookie的值中含有中文时，需要对cookie进行编码，不然会产生乱码
        try {
            URLEncoder.encode(value, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        cookie.setMaxAge(time);
        /*
            将Cookie添加到Response中,使之生效
            addCookie后，如果已经存在相同名字的cookie，则最新的覆盖旧的cookie
        */
        response.addCookie(cookie);
        return response;
    }

    /**
     * 根据cookies名称销毁cookies
     * @param request
     * @param response
     * @param name
     */
    public static void clearCookie(HttpServletRequest request, HttpServletResponse response, String name){
        Map<String, Cookie> cookieMap = readCookieMap(request);
        Cookie cookie = cookieMap.get(name);
        if (cookie != null) {
            cookie.setValue(null);
            cookie.setMaxAge(0);// 立即销毁cookie
            cookie.setPath("/");
            response.addCookie(cookie);
        }
    }
}
